<!--
*@Author: QWP
*@Description: 流程标签页
*@Date: 2024-07-31 10:11:37
-->
<template>
  <a-tabs
    v-model:activeKey="activeKey"
    v-bind="$attrs"
    :tabBarStyle="{ display: show ? '' : 'none' }"
    class="f-h-100 u-flow-tab">
    <slot></slot>
    <a-tab-pane
      key="flow"
      tab="流程记录"
      v-if="show">
      <div v-if="(params || {})['processintsid']">
        <!-- 审核意见 -->
        <template v-if="isAudit && isAuditPage && params['status'] == 2">
          <u-form
            :elements="formEls"
            :model="form"
            ref="formRef"
            style="overflow: hidden"></u-form>
        </template>

        <!-- 流程图 -->
        <u-act-flow :processInstanceId="(params || {})['processintsid']" 
          :show="show == true && open == true"/>

        <!-- 审核记录 -->
        <u-busi-card title="审核记录">
          <u-table
            :columns="recordCols"
            :data="tabData"
            :row-selection="null"
            :scroll="{ y: '400px' }"></u-table>
        </u-busi-card>
      </div>
      <template v-else>
        <a-empty description="暂无流程可查看" />
      </template>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="ts" setup>
defineOptions({
  name: "u-flow-tab",
});
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useBaseStore } from "@/store";
import { storeToRefs } from "pinia";
import { AuditParams } from "@/common/model/auditParams";
import { numberC, alertC, messageC, nullC, isValue } from '@/util/common'
import * as auditApi from "@/service/audit";
import { cloneDeep } from 'lodash'

const { ACTIONTYPE } = storeToRefs(useBaseStore());

interface Props {
  params?: object;
  activeKey?: string;
  show?: boolean;
  isAudit?: boolean;
  isAuditPage?: boolean;
  open?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  activeKey: "flow",
  show: false,
  isAudit: false,
  isAuditPage: false,
});

const emits = defineEmits(["back"]);

let activeKey = ref<string>();

// 审核意见
const formRef = ref();
const form = ref({});
const formEls: Array<_IFormEl> = reactive([
  {
    label: "审核意见",
    key: "msg",
    col: { span: 24 },
    element: "textarea",
    formItemProps: { labelWidth: "120px", colon: false, required: true },
  },
  {
    label: "审核节点",
    key: "selAuditNode",
    element: "select",
    formItemProps: { labelWidth: "120px", colon: false, required: true },
    col: { span: 24 },
    hide: computed(() => selNodeData.value.length == 0),
    componentProps: {
      fieldNames: { label: 'nodeName', value: 'nodeName' },
      options: computed(() => selNodeData.value),
      onChange: (val, item) => selNodeChange(val, item)
    },
  },
  {
    label: "审核人员",
    key: "variables",
    element: "selRoleUserTree",
    formItemProps: { labelWidth: "120px", colon: false, required: true },
    col: { span: 24 },
    hide: computed(() => !isValue(form.value.selAuditNode)),
    componentProps: {
      fieldNames: { label: "name", value: "keyid" },
      multiple: true,
      disabled: true,
      isLoadData: true,
      class: "f-normal-disable",
      checkStrictly: true,
      parent: { key: "roleName", valueKey: "fkparentid", parentTLable: "角色名称" },
    },
  },
]);

const loading = ref<boolean>(false);
const tabData = ref<any[]>([]);
const recordCols: TableColumnProps[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 50,
    align: "center",
    customRender: ({ index }) => (index += 1),
  },
  { title: "节点名称", dataIndex: "usertaskname", minWidth: 150 },
  // { title: '部门', dataIndex: 'bm', width: 150,  },
  { title: "审核人", dataIndex: "username", minWidth: 150 },
  {
    title: "审核情况",
    dataIndex: "actiontype",
    minWidth: 150,
    customRender: ({ text }) => {
      return (ACTIONTYPE.value.find((i) => i.id == text) || { label: "" })["label"];
    },
  },
  { title: "审核时间", dataIndex: "rdt", minWidth: 150, align: "center" },
  { title: "审核意见", dataIndex: "msg", minWidth: 150 },
];

// 获取审核记录
const getHis = async () => {
  loading.value = true;
  try {
    const tParams = AuditParams[props.params["type"]] || {};
    const pParams = props.params;
    const res = await auditApi.getHis({ 
      keyid: nullC(props.params['keyid']), 
      processintsid: nullC(props.params['processintsid']), 
      ...tParams 
    });
    if (res.error == 200) {
      tabData.value = res.result;
      emits("back", tabData.value);
    }
  } catch (error) {}
  loading.value = false;
};

// 判断是否需要选择下一个审核节点
const selNodeData = ref<any[]>([])
const isMustSel = ref<boolean>(false);
const isSelUser = async () => {
  if (props.params["status"] != 2 || props.isAudit == false) {
    return;
  }
  const configParams = AuditParams[props.params["type"]] || {};
  const reportParams = {
    ...configParams,
    ...props.params,
    // fkdycform,
    businessKey: props.params["keyid"],
    processInstanceId: props.params["processintsid"],
  };
  try {
    const res = await auditApi.getNextInfo(reportParams);
    if (res.error == 200 && res.result) {
      isMustSel.value = true;
      selNodeData.value = res.result;
      // form.value.mutiKey = res.result;
    }
  } catch (error) {}
};

const selNodeChange = (val, item) => {
  let tItem = cloneDeep(item)
  delete tItem.nodeName
  let key = Object.keys(tItem).filter(i => i.includes('_byMulit'))
  form.value = { ...form.value, ...tItem, nodeKey: key.length ? key[0] : '' }
  if(!tItem['nodeKey']) {
    form.value.variables = []
  }
}

watch( () => [props.open, props.show], (nval, oval) => {
  if (nval.every(i => i == true)) {
    if (props.params["keyid"] && props.show == true) {
      getHis();
      isSelUser();
    }
  }
},
{ immediate: true, deep: true });

const currntFlowTab = () => {
  activeKey.value = "flow";
};

defineExpose({
  formRef,
  form,
  currntFlowTab,
});
</script>

<style lang="scss">
.u-flow-tab {
  .ant-tabs-content {
    height: 100%;
  }
}
</style>
